﻿#region File Description
// --------------------------------
// <copyright file="MusicPlayer.cs" company="Faculty of Information Technology, Czech Technical University in Prague">
//     This document is shared by Microsoft Public License (MS-PL)
//     For further details please see http://msdn.microsoft.com/en-us/library/ff648068.aspx or license.txt.
// </copyright>
// <author>Vladislav Richter</author>

// <email>richtvl2@fit.cvut.cz</email>

// <date>9. 11. 2011 22:22:37</date>

// <summary>
// 
// </summary>
// ------------------------------------------------------------------------------------------------------
#endregion
using System;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Content;
using System.Collections.Generic;

namespace ExternalClasses.Sounds
{
    /// <summary>
    /// Plays songs from Music library or loads them from content pipeline.
    /// </summary>
    public static class MusicPlayer
    {
        public static Song ActualSong;
        public static bool Repeating, Interrupted, UseMediaLibrary;
        const float VolumeDeltaStep = 0.05f;
        private static MediaLibrary library;
        private static Random rnd;
        private static bool resumePlaying;
        private static bool enabled;

        public static bool Enabled
        {
            get { return enabled; }
            set
            {
                if (value == false && enabled)
                {
                    enabled = value;
                    if (MediaPlayer.State != MediaState.Stopped)
                    {
                        MusicPlayer.Stop();
                    }
                    MediaPlayer.MediaStateChanged -= MediaPlayer_MediaStateChanged;
#if WINDOWS_PHONE
                    Microsoft.Phone.Shell.PhoneApplicationService.Current.Activated -= Current_Activated;
                    Microsoft.Phone.Shell.PhoneApplicationService.Current.Deactivated -= Current_Deactivated;
#endif
                }
                if (value && enabled == false)
                {
                    enabled = value;
                    MediaPlayer.MediaStateChanged += MediaPlayer_MediaStateChanged;
#if WINDOWS_PHONE
                    Microsoft.Phone.Shell.PhoneApplicationService.Current.Activated += Current_Activated;
                    Microsoft.Phone.Shell.PhoneApplicationService.Current.Deactivated += Current_Deactivated;
#endif
                }
                
            }
        }

        static MusicPlayer()
        {
            MediaPlayer.MediaStateChanged += MediaPlayer_MediaStateChanged;
            //MediaPlayer.ActiveSongChanged += MediaPlayer_ActiveSongChanged;
            //MediaPlayer.Volume = 0.03f;
            library = new MediaLibrary();
            
            List<Song> songs = new List<Song>(library.Songs);
            rnd = new Random((int)DateTime.Now.Ticks);


        }

        #if WINDOWS_PHONE
        static void Current_Deactivated(object sender, Microsoft.Phone.Shell.DeactivatedEventArgs e)
        {
            //throw new NotImplementedException();
            resumePlaying = (MediaPlayer.State == MediaState.Playing);
            if (resumePlaying){
                MediaPlayer.Pause();
            }
        }

        static void Current_Activated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
        {
            if (resumePlaying)
            {
                MediaPlayer.Resume();
            }
        }
#endif
        
        public static void Play(ContentManager content, string path, bool repeat)
        {
            if (Enabled)
            {
                try
                {
                    UseMediaLibrary = false;
                    MediaPlayer.IsRepeating = repeat;
                    ActualSong = content.Load<Song>(path);
                    if (ActualSong != null) MediaPlayer.Play(ActualSong);
                    Repeating = repeat;
                }
                catch (Exception exc)
                {
                    Console.Error.WriteLine("{0} {1}", exc.GetType().Name, exc.Message);
                }
            }
        }

        public static void InterruptWithThisSong(Song song)
        {
            if (Enabled)
            {
                try
                {
                    MediaPlayer.Pause();
                    MediaPlayer.IsRepeating = false;
                    Interrupted = true;
                    MediaPlayer.Play(song);
                }
                catch (Exception exc)
                {
                }
            }
        }

        public static void PlayLibrary()
        {
            if (Enabled)
            {
                Stop();
                UseMediaLibrary = true;
                ContinueFromLibrary();
            }
        }

        public static void VolumeUp()
        {
            if (MediaPlayer.Volume < 1 - VolumeDeltaStep)
            {
                MediaPlayer.Volume = MediaPlayer.Volume + VolumeDeltaStep;                
            }
        }

        public static void VolumeDown()
        {
            if (MediaPlayer.Volume >  VolumeDeltaStep)
            {
                MediaPlayer.Volume = MediaPlayer.Volume - VolumeDeltaStep;
            }
        }

        public static void Stop()
        {
            if (Enabled)
            {
                MusicPlayer.UseMediaLibrary = false; // zabrani znovuspusteniu
                MediaPlayer.IsRepeating = false;
                MediaPlayer.Stop();
                //MediaPlayer.Pause();
            }
        }
        
        private static void ContinueFromLibrary()
        {
            //MediaPlayer.Volume = 0.03f;
            MediaPlayer.IsRepeating = Repeating;
            MediaPlayer.IsShuffled = true;
            try
            {
                PlayRandom();
                //MediaPlayer.Play(library.Songs);
                MediaPlayer.IsShuffled = true;
            }
            catch
            {

            }
        }

        public static void PlayRandom()
        {
            if (Enabled)
            {
                MediaPlayer.Play(library.Songs[rnd.Next(library.Songs.Count - 1)]);
            }
        }

        private static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
        {
            if (Enabled)
            {
                if (MediaPlayer.State == MediaState.Stopped)
                {
                    if (Interrupted && UseMediaLibrary == false)
                    {
                        //MediaPlayer.Volume = 0.03f;
                        MediaPlayer.IsRepeating = Repeating;
                        if (ActualSong != null) MediaPlayer.Play(ActualSong);
                    }

                    if (UseMediaLibrary)
                    {
                        ContinueFromLibrary();
                    }

                    Interrupted = false;
                }
                if (UseMediaLibrary && MediaPlayer.State == MediaState.Paused && MediaPlayer.PlayPosition == TimeSpan.FromTicks(0))
                {
                    ContinueFromLibrary();
                }
            }
        }

        public static void Dispose()
        {
            if (Enabled)
            {
                Interrupted = false;
                UseMediaLibrary = false;
                MediaPlayer.Stop();                
            }
            library.Dispose();
        }
    }
}
